package one.stand.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import one.stand.enums.SeeRecordEnums;
import one.stand.model.*;
import one.stand.request.SeeRecordHistoryRequest;
import one.stand.request.SeeRecordRequest;
import one.stand.request.statistics.*;
import one.stand.response.CrmCustomerAnalysisRespnse;
import one.stand.response.CrmSeeRecordResponse;
import one.stand.response.CustomerAnalysisResponse;
import one.stand.response.SeeRecordHistoryResponse;
import one.stand.response.statistics.*;
import one.stand.service.BaseService;
import one.stand.service.SeeRecordService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Administrator
 */
@Service
@Transactional
public class SeeRecordServiceImpl extends BaseService implements SeeRecordService {
    @Override
    public ResultModel<Map<String, Object>> customerAnalysis(SeeRecordRequest recordRequest) {
        log.info("客户与我的互动:{}", JSON.toJSONString(recordRequest));
        // todo
        if (recordRequest == null) {
            return ResultModel.checkParamFail();
        }
        if (recordRequest.getType() == null) {
            recordRequest.setType(2);
        }
        // 客户与自己的沟通次数
        Long imNum = consultRecordMapper.count(new ConsultRecordModel() {{
            if (recordRequest.getUserId() != null) {
                setUserId(recordRequest.getUserId().intValue());
            }
            if (recordRequest.getType() == 1) {
                setCompanyCardId(recordRequest.getMyCardId().intValue());
            } else if (recordRequest.getCardId() != null) {
                setCompanyCardId(recordRequest.getCardId());
            }
            setCompanyId(recordRequest.getCId().intValue());
        }});
        // 获取客户拨打我的电话次数
        Long callsNum = callsPhoneRecordMapper.count(new CallsPhoneRecordModel() {{
            if (recordRequest.getUserId() != null) {
                setUserId(recordRequest.getUserId().intValue());
            }
            if (recordRequest.getType() == 1) {
                setCompanyCardId(recordRequest.getMyCardId().intValue());
            } else if (recordRequest.getCardId() != null) {
                setCompanyCardId(recordRequest.getCardId());
            }
            setCompanyId(recordRequest.getCId().intValue());
        }});
        //商品转发次数
        Long goodForwardNum = goodsForwardRecordMapper.count(new GoodsForwardRecordModel() {{
            if (recordRequest.getUserId() != null) {
                setUserId(recordRequest.getUserId().intValue());
            }
            if (recordRequest.getType() == 1) {
                setCompanyCardId(recordRequest.getMyCardId().intValue());
            } else if (recordRequest.getCardId() != null) {
                setCompanyCardId(recordRequest.getCardId());
            }
            setCompanyId(recordRequest.getCId().intValue());
        }});
        //评论次数
        Long commentNum = commentMapper.count(new CommentModel() {{
            if (recordRequest.getUserId() != null) {
                setUserId(recordRequest.getUserId().intValue());
            }
            if (recordRequest.getType() == 1) {
                setCardId(recordRequest.getMyCardId().intValue());
            } else if (recordRequest.getCardId() != null) {
                setCardId(recordRequest.getCardId());
            }
            setCompanyId(recordRequest.getCId().intValue());
        }});
        //文章转发次数
        Long dynamicNum = dynamicForwardRecordMapper.count(new DynamicForwardRecordModel() {{
            if (recordRequest.getUserId() != null) {
                setUserId(recordRequest.getUserId().intValue());
            }
            if (recordRequest.getType() == 1) {
                setCompanyCardId(recordRequest.getMyCardId().intValue());
            } else if (recordRequest.getCardId() != null) {
                setCompanyCardId(recordRequest.getCardId());
            }
            setCompanyId(recordRequest.getCId().intValue());
        }});
        //客户信息
        CustomerAnalysisResponse analysisModel = new CustomerAnalysisResponse();
        if (recordRequest.getUserId() != null) {
            // 员工卡片，客户id，查看类型（2产品）
            analysisModel = seeRecordMapper.getCustomerAnalysis(recordRequest.getMyCardId(), recordRequest.getUserId().intValue(),
                                                                SeeRecordEnums.PRODUCT.getCode(), recordRequest.getCId().intValue());
            analysisModel.setName(
                            StringUtils.isBlank(analysisModel.getName()) ? "" : new String(Base64.getDecoder().decode(analysisModel.getName().getBytes())));
        }
        Map<String, Object> data = new HashMap<>(8);
        data.put("imNum", imNum);
        data.put("callsNum", callsNum);
        data.put("goodForwardNum", goodForwardNum);
        data.put("commentNum", commentNum);
        data.put("dynamicNum", dynamicNum);
        data.put("analysisModel", analysisModel);
        return ResultModel.success(data);
    }

    @Override
    public ResultModel<List<CrmSeeRecordResponse>> getSeeRecordList(SeeRecordRequest recordRequest) {
        if (recordRequest == null) {
            return ResultModel.checkParamFail();
        } else if (recordRequest.getEntranceType() == null) {
            return ResultModel.checkParamFail("entranceType: EntranceType为空");
        }
        log.info("ai分析：{}", JSON.toJSONString(recordRequest));
        //ai分析验证 和行为追踪都需要查看类型
        if (recordRequest.getEntranceType() == 3 || recordRequest.getEntranceType() == 2) {
            if (recordRequest.getSeeType() == null) {
                return ResultModel.checkParamFail("查看类型为空");
            }
        }
        //时间追踪不需要查看类型
        if (recordRequest.getEntranceType() == 1 || recordRequest.getEntranceType() == 4) {
            recordRequest.setSeeType(null);
        }
        PageHelper.startPage(recordRequest.getPageNum(), recordRequest.getPageSize());
        List<CrmSeeRecordModel> crmSeeRecordModels = seeRecordMapper.getCrmSeeRecord(recordRequest.getUserId(), recordRequest.getEntranceType(),
                                                                                     recordRequest.getSeeType(), recordRequest.getMyCardId());
        PageInfo<CrmSeeRecordModel> pageInfo = new PageInfo(crmSeeRecordModels);
        List<CrmSeeRecordResponse> crmSeeRecordResponseList = new ArrayList<>();
        pageInfo.getList().forEach(c -> {
            CrmSeeRecordResponse recordResponse = new CrmSeeRecordResponse();
            BeanUtils.copyProperties(c, recordResponse);
            recordResponse.setNickName(StringUtils.isBlank(c.getNickName()) ? "" : new String(java.util.Base64.getDecoder().decode(c.getNickName())));
            recordResponse.setName(recordResponse.getNickName());
            crmSeeRecordResponseList.add(recordResponse);
        });
        return ResultModel.success(crmSeeRecordResponseList);
    }

    @Override
    public ResultModel<List<CrmCustomerAnalysisRespnse>> countCustomerAnalysis(SeeRecordRequest recordRequest) {
        if (recordRequest == null) {
            return ResultModel.checkParamFail();
        }
        log.info("圆饼图：{}", JSON.toJSONString(recordRequest));
        SeeRecordModel model = new SeeRecordModel();
        BeanUtils.copyProperties(recordRequest, model);
        if (recordRequest.getCardId() == null) {
            model.setCardId(recordRequest.getMyCardId());
        } else if (recordRequest.getType() != null && recordRequest.getType() == 1) {
            model.setCardId(recordRequest.getCardId());
        }
        if (recordRequest.getUserId() != null) {
            model.setUserId(recordRequest.getUserId().intValue());
        }
        model.setCompanyId(recordRequest.getCId().intValue());
        List<CrmCustomerAnalysisRespnse> list = seeRecordMapper.countCustomerAnalysis(model);
        if (list == null || list.size() <= 0) {
            return ResultModel.noData();
        }
        return ResultModel.success(list);
    }

    @Override
    public ResultModel<Map<String, Object>> getPcCount(SeeRecordRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        log.info("CRM-PC端首页统计:{}", JSON.toJSONString(request));
        SeeRecordModel model = new SeeRecordModel();
        if (ONE.equals(request.getType())) {
            model.setCardId(request.getMyCardId().intValue());
        } else {
            model.setCompanyId(request.getCId().intValue());
        }
        Map<String, Object> map = seeRecordMapper.getPcCount(model);
        if (map == null) {
            return ResultModel.noData();
        }
        // 查询未跟进客户头像-最多5张
        map.put("photos", seeRecordMapper.getPcPhotos(model));
        // 查询今日录入客户列表
        map.put("newCustomerList", seeRecordMapper.selectPcIndexCustomer(model));
        return ResultModel.success(map);
    }

    @Override
    public ResultModel<Map<String, Object>> getChangeCount(SeeRecordRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        log.info("CRM-PC端首页转化率漏斗:{}", JSON.toJSONString(request));
        SeeRecordModel model = new SeeRecordModel();
        if (ONE.equals(request.getType())) {
            model.setCardId(request.getMyCardId().intValue());
        }
        if (request.getDayNum() == null) {
            model.setDayNum(30);
        } else {
            model.setDayNum(request.getDayNum());
        }
        model.setCompanyId(request.getCId().intValue());
        Map<String, Object> list = seeRecordMapper.getChangeCount(model);
        if (list == null || list.size() <= 0) {
            return ResultModel.noData();
        }
        model.setSeeType(2);
        list.put("seeGoodsNum", seeRecordMapper.getChangeCountOne(model));
        return ResultModel.success(list);
    }

    @Override
    public ResultModel<SituationVisitStatisticsResponse> situationStatistics(SituationVisitStatisticsRequest request) {
        LocalDate now = LocalDate.now();
        String beginDate;
        String endDate;
        beginDate = now.toString();
        endDate = now.plusDays(1).toString();

        SituationVisitStatisticsResponse response = new SituationVisitStatisticsResponse();

        BusinessVisitStatistics visitCount = seeRecordMapper.visitStatistics(request.getCompanyId(), request.getMyCardId(), beginDate, endDate);
        if (visitCount != null) {
            response.setVisitUserCount(visitCount.getVisitUserCount());
            response.setVisitNewUserCount(visitCount.getVisitNewUserCount());
            response.setVisitCount(visitCount.getVisitCount());
        }
        beginDate = now.plusDays(-1).toString();
        endDate = now.toString();
        BusinessVisitStatistics yesterdayVisitCount = seeRecordMapper.visitStatistics(request.getCompanyId(), request.getMyCardId(), beginDate, endDate);
        if (yesterdayVisitCount != null) {
            response.setYesterdayVisitUserCount(yesterdayVisitCount.getVisitUserCount());
            response.setYesterdayVisitNewUserCount(yesterdayVisitCount.getVisitNewUserCount());
            response.setYesterdayVisitCount(yesterdayVisitCount.getVisitCount());
        }

        return ResultModel.success(response);
    }

    @Override
    public ResultModel<List<CrmSeeRecordResponse>> getVisitRankingList(VisitRankingRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }

        BeginAndEndDateWrapper beginAndEndDateWrap = BeginAndEndDateWrapper.build(request.getTimeType());
        String beginDate = beginAndEndDateWrap.getBeginDate();
        String endDate = beginAndEndDateWrap.getEndDate();
        PageHelper.startPage(request.getPageNum(), request.getPageSize());

        // 访问排名替换成访问记录，通过时间倒序排列
//        List<CrmSeeRecordModel> crmSeeRecordModels = seeRecordMapper.getVisitRanking(request.getMyCardId(), request.getSeeType(), beginDate, endDate);

        List<CrmSeeRecordModel> crmSeeRecordModels = seeRecordMapper.getSeeRecords(request.getMyCardId(), request.getSeeType(), beginDate, endDate);

        PageInfo<CrmSeeRecordModel> pageInfo = new PageInfo(crmSeeRecordModels);

        List<CrmSeeRecordResponse> crmSeeRecordResponseList = pageInfo.getList().stream().map(csr -> {
            CrmSeeRecordResponse recordResponse = new CrmSeeRecordResponse();
            BeanUtils.copyProperties(csr, recordResponse);
            recordResponse.setNickName(StringUtils.isBlank(csr.getNickName()) ? "" : new String(Base64.getDecoder().decode(csr.getNickName())));
            recordResponse.setName(recordResponse.getNickName());
            return recordResponse;
        }).collect(Collectors.toList());
        return ResultModel.success(crmSeeRecordResponseList);

    }

    @Override
    public ResultModel<List<VisitGoodsTopResponse>> getVisitGoodsTopN(VisitGoodsTopRequest request) {
        BeginAndEndDateWrapper beginAndEndDateWrap = BeginAndEndDateWrapper.build(request.getTimeType());
        String beginDate = beginAndEndDateWrap.getBeginDate();
        String endDate = beginAndEndDateWrap.getEndDate();
        List<VisitGoodsTopResponse> responses = seeRecordMapper.getVisitGoodsTopN(request.getCompanyId(), request.getMyCardId(), request.getUserId(),
                                                                                  request.getTopN(), beginDate, endDate);
        return ResultModel.success(responses);
    }

    @Override
    public ResultModel<VisitMallStatisticsResponse> visitMallStatistics(VisitMallStatisticsRequest request) {
        VisitMallStatisticsResponse response = new VisitMallStatisticsResponse();
        BeginAndEndDateWrapper beginAndEndDateWrap = BeginAndEndDateWrapper.build(request.getTimeType());
        String beginDate = beginAndEndDateWrap.getBeginDate();
        String endDate = beginAndEndDateWrap.getEndDate();
        // 商城访问次数
        Integer visitCount = seeRecordMapper.statisticsBySeeType(request.getCompanyId(), 2, beginDate, endDate);
        response.setVisitCount(visitCount);
        // 成交笔数 成交总价
        VisitMallStatisticsResponse delOrder = seeRecordMapper.statisticsOrderWithDeal(request.getCompanyId(), beginDate, endDate);
        response.setPerUserPrices(delOrder.getPerUserPrices());
        response.setDealCount(delOrder.getDealCount());

        return ResultModel.success(response);
    }

    @Override
    public ResultModel<List<DealRateTopNResponse>> dealRateTopN(DealRateTopNRequest request) {
        BeginAndEndDateWrapper beginAndEndDateWrap = BeginAndEndDateWrapper.build(request.getTimeType());
        String beginDate = beginAndEndDateWrap.getBeginDate();
        String endDate = beginAndEndDateWrap.getEndDate();

        List<DealRateTopNResponse> responses = seeRecordMapper.dealRateTopN(request.getCompanyId(), request.getMyCardId(), request.getUserId(),
                                                                            request.getTopN(), beginDate, endDate)
                                                              .stream()
                                                              .peek(d -> d.setNickName(StringUtils.isBlank(d.getNickName()) ?
                                                                                       "" :
                                                                                       new String(Base64.getDecoder().decode(d.getNickName()))))
                                                              .peek(d -> {
                                                                  if (d.getRate() < 8.88) {
                                                                      d.setRate(8.88);
                                                                  } else if (d.getRate() > 89.99) {
                                                                      d.setRate(89.99);
                                                                  }
                                                              })
                                                              .collect(Collectors.toList());
        return ResultModel.success(responses);
    }

    @Override
    public ResultModel<List<SeeRecordHistoryResponse>> getSeeRecordHistory(SeeRecordHistoryRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        } else if (request.getUserId() == null) {
            return ResultModel.checkParamFail("客户ID为空");
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<SeeRecordHistoryResponse> seeRecordHistory = seeRecordMapper.getSeeRecordHistory(request.getUserId(), request.getMyCardId());
        PageInfo<CrmSeeRecordModel> pageInfo = new PageInfo(seeRecordHistory);
        return ResultModel.success(pageInfo.getList());
    }

    @Override
    public ResultModel<TimeVisitStatisticsResponse> timeStatistics(TimeVisitStatisticsRequest request) {
        TimeVisitStatisticsResponse response = new TimeVisitStatisticsResponse();
        List<TimeVisitStatisticsResponseCell> cells;
        LocalDate now = LocalDate.now();

        String beginDate;
        String endDate;
        switch (request.getTimeType()) {
        case 1:
            beginDate = now.plusDays(-1).toString();
            endDate = now.toString();
            cells = seeRecordMapper.timeStatisticsInterval2Hour(request.getCompanyId(), request.getMyCardId(), request.getBusinessType(), beginDate, endDate);
            break;
        case 2:
            beginDate = now.plusDays(-7).toString();
            endDate = now.toString();
            cells = seeRecordMapper.timeStatisticsIntervalDay(request.getCompanyId(), request.getMyCardId(), request.getBusinessType(), beginDate, endDate);
            break;
        case 3:
            beginDate = now.plusMonths(-1).toString();
            endDate = now.toString();
            cells = seeRecordMapper.timeStatisticsIntervalDay(request.getCompanyId(), request.getMyCardId(), request.getBusinessType(), beginDate, endDate);
            break;
        default:
            beginDate = now.toString();
            endDate = now.plusDays(1).toString();
            cells = seeRecordMapper.timeStatisticsInterval2Hour(request.getCompanyId(), request.getMyCardId(), request.getBusinessType(), beginDate, endDate);
        }
        // 今天 昨天 时间2小时间隔
        // 7天 每一天
        response.setTimeType(request.getTimeType());
        response.setBusinessType(request.getBusinessType());
        response.setTotal(cells.stream().mapToInt(TimeVisitStatisticsResponseCell::getCount).sum());
        response.setCell(cells);

        return ResultModel.success(response);
    }

    @Override
    public ResultModel<SceneVisitStatisticsResponse> sceneStatistics(SceneVisitStatisticsRequest request) {
        BeginAndEndDateWrapper beginAndEndDateWrap = BeginAndEndDateWrapper.build(request.getTimeType());
        String beginDate = beginAndEndDateWrap.getBeginDate();
        String endDate = beginAndEndDateWrap.getEndDate();

        List<BusinessVisitStatistics> businessStatistics = seeRecordMapper.visitGroupStatistics(request.getCompanyId(), request.getMyCardId(), beginDate,
                                                                                                endDate);

        SceneVisitStatisticsResponse response = new SceneVisitStatisticsResponse();
        response.setTimeType(request.getTimeType());
        businessStatistics.forEach(v -> {
            // 1:名片;2:产品;3：官网;4:查看文章;5:预约
            switch (v.getBusinessType()) {
            case 1:
                response.getVisitCount().setCardCount(v.getVisitCount());
                response.getVisitNewUserCount().setCardCount(v.getVisitNewUserCount());
                response.getVisitUserCount().setCardCount(v.getVisitUserCount());
                break;
            case 2:
                response.getVisitCount().setShopCount(v.getVisitCount());
                response.getVisitNewUserCount().setShopCount(v.getVisitNewUserCount());
                response.getVisitUserCount().setShopCount(v.getVisitUserCount());
                break;
            case 3:
                response.getVisitCount().setWebCount(v.getVisitCount());
                response.getVisitNewUserCount().setWebCount(v.getVisitNewUserCount());
                response.getVisitUserCount().setWebCount(v.getVisitUserCount());
                break;
            case 4:
                response.getVisitCount().setDynamicCount(v.getVisitCount());
                response.getVisitNewUserCount().setDynamicCount(v.getVisitNewUserCount());
                response.getVisitUserCount().setDynamicCount(v.getVisitUserCount());
                break;
            case 5:
                response.getVisitCount().setAppointmentCount(v.getVisitCount());
                response.getVisitNewUserCount().setAppointmentCount(v.getVisitNewUserCount());
                response.getVisitUserCount().setAppointmentCount(v.getVisitUserCount());
                break;
            }
        });
        return ResultModel.success(response);
    }
}
